#!/usr/bin/env python
# _*_coding:utf-8_*_

"""
@author:gao
@file: testDemo.py
@time: 2018/09/{DAY}
"""
from PySide6 import QtWidgets
from my_thread.my_thread_pool import MyThreadPool
from my_thread.control_switch_thread import ControlSwitchThread
from my_thread.measurement_thread import MeasurementThread
from my_thread.save_data2file_thread import SaveDataToFile
from my_thread.write_data2file_thread import WriteDataToFile as wdtf
from PySide6.QtWidgets import *
from PySide6.QtCore import *
from PySide6.QtGui import QBrush, QColor
import sys
import collections
import time
import os
import operator
from functools import reduce
from driver.switch_driver import get_com_list
from gui.mainWindow import Ui_MainWindow
from my_log.logger import logger


class Main(QtWidgets.QMainWindow, Ui_MainWindow):
    stop_signal = Signal()

    def __init__(self):
        super(Main, self).__init__()
        self.setupUi(self)
        self.showMaximized()
        self.pool = MyThreadPool().get_instance()
        self.row = 0
        self.update_time()
        self.prefix_path = None
        self.init_com()

    def init_com(self):
        com_list = self.get_com_info()
        if com_list:
            self.cbb_com.addItems(com_list)
        else:
            self.show_warnning("提示", "没有可用的串口设备")

    def get_com_info(self):
        try:
            com_list = get_com_list()
        except Exception as e:
            logger.error("get_com_info," + str(e))
            return None
        else:
            return com_list

    def start_e5080_test(self, value, num):
        if value == 1:
            self.num = num
            self.test_thread.resume()

    def show_result(self, status, value_list):
        if status:
            # print("value_list", value_list)
            self.savedata2file(self.num, value_list)
            self.write_data_2_grid(self.num, value_list)
            self.control_switch.status = 0
            self.control_switch.pause()
            self.control_switch.resume()

    def go_to(self):
        self.control_switch.status = 1
        self.control_switch.pause()
        self.control_switch.resume()

    def update_time(self):
        # 创建定时器
        self.Timer = QTimer()
        # 定时器每500ms工作一次
        self.Timer.start(500)
        # 建立定时器连接通道  注意这里调用TimeUpdate方法，不是方法返回的的结果，所以不能带括号，写成self.TimeUpdate()是不对的
        self.Timer.timeout.connect(self.timeUpdate)

    def timeUpdate(self):
        self.l_time.setText(QDateTime.currentDateTime().toString('yyyy-MM-dd hh:mm:ss dddd'))

    @Slot()
    def on_action_save_data_triggered(self):
        self.sample_common()

    @Slot()
    def on_action_exit_triggered(self):
        self.close()

    @Slot()
    def on_action_start_triggered(self):
        if self.prefix_path:
            self.num = self.le_num.text().strip()
            com_list = self.cbb_com.currentText().strip()
            if com_list:
                self.com_list = com_list.split(",")
            self.control_switch = ControlSwitchThread(self.com_list[0], self.num)
            self.control_switch.singal.startSignal.connect(self.start_e5080_test)
            self.pool.start(self.control_switch)
            e5080b = "USB0::0x2A8D::0x7901::MY59101311::0::INSTR"
            self.test_thread = MeasurementThread(e5080b)
            self.test_thread.singal.resultSignal.connect(self.show_result)
            self.test_thread.singal.finishSignal.connect(self.go_to)
            self.pool.start(self.test_thread)
            self.action_start.setEnabled(False)
            self.action_stop.setEnabled(True)
        else:
            self.show_warnning("提示", "请设置文件保存路径！")

    @Slot()
    def on_action_stop_triggered(self):
        self.stop_signal.emit()
        self.action_start.setEnabled(True)
        self.action_stop.setEnabled(False)

    @Slot()
    def on_action_set_file_path_triggered(self):
        prefix_path = QFileDialog.getExistingDirectory(self, "选择文件保存文件夹", "\\")
        if prefix_path:
            self.prefix_path = prefix_path
        else:
            self.show_warnning("提示", "请选择文件保存的文件夹")

    def write_finish(self, value):
        if 1 == value:
            self.show_notification("提示", "导出数据成功！")
        else:
            self.show_warnning("提示", "导出数据失败！")

    def write_data_2_grid(self, row, data_list):
        self.tw_data.setRowCount(row)
        self.tw_data.verticalScrollBar().setValue(row)
        handle_list = self.handle_list(data_list)
        handle_list.append(row)

        if handle_list:
            for i in range(len(handle_list)):
                self.tw_data.setItem(row - 1, i, QTableWidgetItem(str(handle_list[i])))
                if i == 0:
                    if float(handle_list[i]) < 0.2:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(0, 255, 0)))
                    else:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(255, 0, 0)))

                if i == 1:
                    if float(handle_list[i]) < 0.4:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(0, 255, 0)))
                    else:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(255, 0, 0)))

                if i == 2:
                    if float(handle_list[i]) < 0.5:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(0, 255, 0)))
                    else:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(255, 0, 0)))

                if i == 3:
                    if float(handle_list[i]) < 0.5:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(0, 255, 0)))
                    else:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(255, 0, 0)))
                if i == 5:
                    if float(handle_list[i]) < 1.25:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(0, 255, 0)))
                    else:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(255, 0, 0)))

                if i == 6:
                    if float(handle_list[i]) < 1.4:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(0, 255, 0)))
                    else:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(255, 0, 0)))

                if i == 7:
                    if float(handle_list[i]) < 1.5:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(0, 255, 0)))
                    else:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(255, 0, 0)))

                if i == 8:
                    if float(handle_list[i]) < 1.5:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(0, 255, 0)))
                    else:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(255, 0, 0)))

                if i == 10:
                    if float(handle_list[i]) < -80:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(0, 255, 0)))
                    else:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(255, 0, 0)))

                if i == 11:
                    if float(handle_list[i]) < -80:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(0, 255, 0)))
                    else:
                        self.tw_data.item(row - 1, i).setBackground(QBrush(QColor(255, 0, 0)))

    def handle_list(self, multi_list):
        if multi_list:
            return reduce(operator.add, multi_list)

    def savedata2file(self, row, data_list):
        handle_list = self.handle_list(data_list)
        handle_list.append(row)
        # print("handle_list",handle_list)
        if self.prefix_path:
            file_path = os.path.join(self.prefix_path,
                                     "test.csv")
            self.saveDataToFile = SaveDataToFile(file_path, handle_list)
            self.pool.start(self.saveDataToFile)


    def get_grid_data(self, table):
        rows = table.rowCount()
        columns = table.columnCount()
        data_list = []
        if rows:
            for i in range(rows):
                row_list = []
                for j in range(columns):
                    if table.item(i, j):
                        item_text = table.item(i, j).text()
                        if item_text:
                            row_list.append(item_text)
                if row_list:
                    data_list.append(row_list)
            return data_list

    def sample_common(self):
        fileName, _ = QFileDialog.getSaveFileName(self, "保存数据", os.getcwd(), "Data files(*.csv *.xlsx)")
        if fileName:
            rows = self.tw_data.rowCount()
            columns = self.tw_data.columnCount()
            data_list = []
            try:
                if rows:
                    for i in range(rows):
                        row_list = []
                        for j in range(columns):
                            if self.tw_data.item(i, j):
                                row_list.append(self.tw_data.item(i, j).text())
                        data_list.append(row_list)
                else:
                    self.show_warnning("提示", "表格中还没有数据，请测试完毕后保存数据")
            except Exception as e:
                logger.error("on_action_save_data_triggered," + str(e))
                self.show_warnning("提示", "表格中还没有数据，请测试完毕后保存数据")
            else:
                self.header = []
                for i in range(columns):
                    if self.tw_data.horizontalHeaderItem(i):
                        header_title = self.tw_data.horizontalHeaderItem(i).text().strip()
                        self.header.append(header_title)
                self.save_data2file(fileName, self.header, data_list)
        else:
            self.show_warnning("提示", "还没有选择保存路径！")

    def save_data2file(self, file_name, header, data_list):
        if file_name and data_list:
            self.writeDataThread = wdtf(file_name, header, data_list)
            self.writeDataThread.signal.finishSignal.connect(self.write_finish)
            self.pool.start(self.writeDataThread)

    def current_report(self):
        data_list = self.get_grid_data(self.tw_data)
        header = [self.tw_data.horizontalHeaderItem(i).text() for i in range(self.tw_data.columnCount())]
        fileName, _ = QFileDialog.getSaveFileName(self, "保存数据", os.getcwd(), "Data files(*.csv *.xlsx)")
        if fileName:
            if data_list:
                self.write_2_csv = WriteData2CSV(fileName, data_list, header)
                self.write_2_csv.signal.write_state.connect(self.write_result)
                self.pool.start(self.write_2_csv)
            else:
                self.show_warnning("提示", "没有数据！")

    def closeEvent(self, event):

        result = QtWidgets.QMessageBox.question(
            self,
            "确认退出...",
            "是否退出程序?",
            QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
        if result == QtWidgets.QMessageBox.Yes:
            try:
                self.pool.clear()
            except Exception as e:
                logger.error("closeEvent:" + str(e))
            finally:
                event.accept()
        else:
            event.ignore()

    def show_notification(self, title, content):
        QMessageBox.information(self, title, content,
                                QMessageBox.Yes, QMessageBox.Yes)

    def show_warnning(self, title, content):
        QMessageBox.warning(self, title, content,
                            QMessageBox.Yes, QMessageBox.Yes)


if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = Main()
    main.show()
    sys.exit(app.exec())
